// More on defining blocks:
// https://developers.google.com/blockly/guides/create-custom-blocks/define-blocks
import * as Blockly from 'blockly/core'

// 1-----格式化时间----------------------------------
const momentFormatJson = {
  type: 'moment_format',
  message0: '将时间 %1 转化为 %2 格式',
  args0: [
    // 动态生成选项
    {
      'type': 'input_value',
      'name': 'DATE_INPUT'
    },
    {
      'type': 'input_dummy',
      'name': 'TYPE_INPUT'
    }
  ],
  extensions: ['date_format_extension'],
  output: null,
  inputsInline: true,
  colour: 160,
  tooltip: '',
  helpUrl: ''
}

Blockly.Extensions.register('date_format_extension',
  function () {
    this.getInput('TYPE_INPUT')
      .appendField(new Blockly.FieldDropdown(
        function () {
          var options = [
            ['年-月-日 时:分:秒', 'YYYY-MM-DD HH:mm:ss'],
            ['年-月-日 时:分', 'YYYY-MM-DD HH:mm'],
            ['年-月-日', 'YYYY-MM-DD'],
            ['年-月', 'YYYY-MM'],
            ['年', 'YYYY']
          ]
          return options
        }), 'Format')
  })

// 创建积木
Blockly.Blocks['moment_format'] = {
  init: function () {
    this.jsonInit(momentFormatJson)
  }
}

Blockly.JavaScript['moment_format'] = function (block) {
  const date = Blockly.JavaScript.valueToCode(block, 'DATE_INPUT',
    Blockly.JavaScript.ORDER_COMMA)
  const type = block.getFieldValue('Format')
  const code = `context.moment(${date}).format('${type}')`
  return [code, Blockly.JavaScript.ORDER_COMMA]
}

// 2 --将时间转换为时间戳-----------------------------------------

const momentTimestampJson = {
  type: 'moment_format_timestamp',
  message0: '将时间 %1 转化为时间戳',
  args0: [
    // 动态生成选项
    {
      'type': 'input_value',
      'name': 'DATE_INPUT'
    }
  ],
  output: null,
  inputsInline: true,
  colour: 160,
  tooltip: '',
  helpUrl: ''
}
Blockly.Blocks['moment_format_timestamp'] = {
  init: function () {
    this.jsonInit(momentTimestampJson)
  }
}

Blockly.JavaScript['moment_format_timestamp'] = function (block) {
  const date = Blockly.JavaScript.valueToCode(block, 'DATE_INPUT',
    Blockly.JavaScript.ORDER_COMMA)
  const code = `context.moment(${date}).valueOf()`
  return [code, Blockly.JavaScript.ORDER_COMMA]
}
